﻿using FreeSql;
using LdtCommonFreeSql;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace LdtJudge.DataEngine.CallInterface.CommHelp
{
    public class FreeSQLHelp
    {
        public static FreesqlDb freesqlDb;
        public static IConfiguration _configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();

        private static ConcurrentDictionary<string, IFreeSql> concurrentDictionaryCon = new ConcurrentDictionary<string, IFreeSql>();
        /// <summary>
        /// 获取语句对象
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static IFreeSql GetFreeSQL(string code)
        {
           
            if (concurrentDictionaryCon.ContainsKey(code.ToLower()))
            {
                return concurrentDictionaryCon[code.ToLower()];
            }
            else
            {
                var s = Task.Run(() => freesqlDb.GetFreeSql(code));
                //var sqlite = new FreeSqlBuilder().UseConnectionString(DataType.Sqlite, "data soure=:" + code).UseAutoSyncStructure(true).Build();
                concurrentDictionaryCon.TryAdd(code.ToLower(), s.Result);
                var dd = s.Result;

                //dd.Aop.CurdAfter += (s, e) =>
                //{
                //    Write("G://52服务器SQLSERVER.csv", "\""+e.Sql + "\""+", 时间:," + e.ElapsedMilliseconds.ToString("0.00"));
                //};
                return dd;
            }
            
        }


        public static void UpdateFreeSql(string key,IFreeSql freeSql) 
        {
            if (concurrentDictionaryCon.ContainsKey(key.ToLower()))
            {
                concurrentDictionaryCon[key.ToLower()] = freeSql;
            }
            else
            {
                concurrentDictionaryCon.TryAdd(key.ToLower(), freeSql);
            }


        }



        /// <summary>
        /// 写入文本文件
        /// </summary>
        /// <param name="fileName">写入的文本文件的路径及文件名（含扩展名）</param>
        /// <param name="strContent">写的内容</param>
        public static void Write(string fileName, string strContent)
        {
            if (!File.Exists(fileName))
            {
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                long fl = fs.Length;
                fs.Seek(fl, SeekOrigin.End);
                sw.WriteLine(strContent);//开始写入值
                sw.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                long fl = fs.Length;
                fs.Seek(fl, SeekOrigin.Begin);
                sw.WriteLine(strContent + "\n\n");//开始写入值
                sw.Close();
                fs.Close();
            }
        }

        /// <summary>
        /// 返回解析的配置中心路径
        /// </summary>
        /// <returns></returns>
        public static string GetConfigConn()
        {
            string b = _configuration["appSettings:setting_center_address"];

            return Convert.ToString(_configuration["appSettings:setting_center_address"]);
        }

        public static void SetConfiguration(string settingCenterStr)
        {
            _configuration["appSettings:setting_center_address"] = settingCenterStr;
        }

        public static void ClearDic()
        {
            concurrentDictionaryCon.Clear();
        }
    }
}
